﻿using Lihong.Cms.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Lihong.Cms.Data
{
    public class UserData : IBaseData<User>
    {
        Db db = new Db();

        public bool Add(User u)
        {
            if (u == null) { return false; }
            foreach (User item in db.Users)
            {
                if (item.Id == u.Id)
                {
                    return false;
                }
            }
            db.Users.Add(u);
            return true;
        }

        //bool Find(User u)
        //{
        //    return u.Id == 3;
        //}

        //Basic

        public bool Delete(int id)
        {
            //Func<User, bool> f = (u) =>
            //{
            //    return u.Id == id;
            //};

            //f=Find;

            //f = x => x.Id == id; //匿名函数   => lambda表达式

            //linq查询  委托
            User u = db.Users.FirstOrDefault(x => x.Id == id);
            if (u == null) return false;
            db.Users.Remove(u);
            return true;
        }

        public User Get(int id)
        {
            return db.Users.FirstOrDefault(x => x.Id == id);
        }

        public ICollection<User> GetAll()
        {
            return db.Users;
        }

        public void Save()
        {
            throw new NotImplementedException();
        }

        public bool Update(User u)
        {
            User d = db.Users.FirstOrDefault(x => x.Id == u.Id);
            if (d == null) return false;
            //d.Email = u.Email;
            //d.Phone = u.Phone;
            //d.Avator = u.Avator;
            //d.NickName = u.NickName;
            //d.UserName = u.UserName;
            // 使用反射，把u的每一个属性值都赋给d对应的属性
            Type type = typeof(User);  // u.GetType();      取类型
            PropertyInfo[] properties = type.GetProperties();   //取类型中的所有public属性
            foreach (PropertyInfo property in properties)   //循环取这些属性
            {
                object o = property.GetValue(u);    //取得u中某个属性的值 为o
                property.SetValue(d, o);    //把o赋值给d中的某个属性
            }
            return true;
        }
    }
}
